import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:lmmi/common/index.dart';

class TimeCapsulePage extends ConsumerStatefulWidget {
  const TimeCapsulePage({super.key});

  @override
  ConsumerState<TimeCapsulePage> createState() => _TimeCapsulePageState();
}

class _TimeCapsulePageState extends ConsumerState<TimeCapsulePage> {
  final TextEditingController _textController = TextEditingController();
  String _selectedTime = '';

  @override
  void initState() {
    super.initState();
    // 重置创建状态，确保每次进入页面都是干净的状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(timeCapsuleProvider.notifier).resetCreateState();
    });

    // 监听文字输入变化
    _textController.addListener(() {
      ref
          .read(timeCapsuleProvider.notifier)
          .updateContent(_textController.text);
    });
  }

  @override
  void dispose() {
    _textController.dispose();

    super.dispose();
  }

  // 选择图片
  Future<void> _pickImage() async {
    await ref.read(timeCapsuleProvider.notifier).pickImage();
  }

  // 删除图片
  void _removeImage() {
    ref.read(timeCapsuleProvider.notifier).removeImage();
  }

  // 获取完整图片路径
  Future<String?> _getFullImagePath(String relativePath) async {
    // 兼容旧数据：绝对路径直接返回
    if (relativePath.startsWith('/')) {
      return relativePath;
    }
    // 新数据：动态构建完整路径
    return await ImagePickerUtil.getFullImagePath(relativePath);
  }

  // 显示时间选择弹窗
  void _showTimeSelectionDialog() {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return _TimeSelectionDialog(
          onTimeSelected: (selectedTime) {
            setState(() {
              _selectedTime = selectedTime;
            });
            _createTimeCapsule();
          },
        );
      },
    );
  }

  // 创建时间胶囊
  Future<void> _createTimeCapsule() async {
    final content = _textController.text.trim();
    if (content.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please enter some content')),
      );
      return;
    }

    // 使用provider创建临时时间胶囊
    final timeCapsule = await ref
        .read(timeCapsuleProvider.notifier)
        .createTemporaryTimeCapsule(_selectedTime);

    if (timeCapsule != null) {
      // 跳转到邮箱输入页面，携带timeCapsule参数
      if (mounted) {
        context.push(AppRoutes.emailInput, extra: timeCapsule);
      }
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Failed to create time capsule')),
        );
      }
    }
  }

  // 构建图片加载动画组件
  Widget _buildImageLoadingWidget() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        color: Colors.grey.withValues(alpha: 0.05),
      ),
      child: Stack(
        children: [
          // 背景脉冲动画
          _buildPulseAnimation(),
          // 中心加载内容
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 图片图标
                Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.r),
                    boxShadow: [
                      BoxShadow(
                        color: Color(0xFFFF7700).withValues(alpha: 0.2),
                        blurRadius: 12.r,
                        offset: Offset(0, 4.r),
                      ),
                    ],
                  ),
                  child: Icon(
                    Icons.image,
                    color: Color(0xFFFF7700),
                    size: 30.sp,
                  ),
                ),
                SizedBox(height: 16.h),
                // 加载动画
                SizedBox(
                  width: 24.w,
                  height: 24.w,
                  child: CircularProgressIndicator(
                    strokeWidth: 2.w,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      Color(0xFFFF7700),
                    ),
                  ),
                ),
                SizedBox(height: 12.h),
                // 加载文字
                Text(
                  'Processing image...',
                  style: TextStyle(
                    color: Color(0xFFFF7700),
                    fontSize: 14.sp,
                    fontFamily: 'Quicksand',
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建脉冲动画背景
  Widget _buildPulseAnimation() {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 1500),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        return Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            gradient: RadialGradient(
              center: Alignment.center,
              radius: value * 1.5,
              colors: [
                Color(0xFFFF7700).withValues(alpha: 0.1 * (1 - value)),
                Color(0xFFFF7700).withValues(alpha: 0.05 * (1 - value)),
                Colors.transparent,
              ],
            ),
          ),
        );
      },
      onEnd: () {
        // 重复动画
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  // 构建成功上传覆盖层
  Widget _buildSuccessOverlay() {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          color: Colors.black.withValues(alpha: 0.6),
        ),
        child: TweenAnimationBuilder<double>(
          duration: Duration(milliseconds: 600),
          tween: Tween(begin: 0.0, end: 1.0),
          builder: (context, value, child) {
            return Center(
              child: Transform.scale(
                scale: value,
                child: Container(
                  width: 80.w,
                  height: 80.w,
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(40.r),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.green.withValues(alpha: 0.3),
                        blurRadius: 20.r,
                        offset: Offset(0, 4.r),
                      ),
                    ],
                  ),
                  child: Icon(Icons.check, color: Colors.white, size: 40.sp),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final timeCapsuleState = ref.watch(timeCapsuleProvider);
    final selectedImagePath = timeCapsuleState.imagePath;
    final isLoadingImage = timeCapsuleState.isLoadingImage;
    final imageUploadSuccess = timeCapsuleState.imageUploadSuccess;
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(
          'Time Capsule',
          style: TextStyle(
            color: Colors.black,
            fontSize: 24.sp,
            fontFamily: 'Port',
            fontWeight: FontWeight.w400,
            height: 0.83,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios_new_rounded,
            color: Colors.black,
            size: 22.sp,
          ),
          onPressed: () {
            if (Navigator.canPop(context)) {
              context.goBack();
            } else {
              context.navigateTo(AppRoutes.main);
            }
          },
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.check, color: Colors.black, size: 22.sp),
            onPressed: _showTimeSelectionDialog,
          ),
        ],
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.timeCapsuleBg),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          top: false,
          bottom: false,
          child: Stack(
            children: [
              Positioned(
                left: 13.w,
                top: 108.h,
                right: 14.w,
                bottom: 35.h,
                child: Container(
                  width: 348.w,
                  height: 669.h,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                      side: BorderSide(
                        width: 1,
                        color: const Color(0xFFFF7700),
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 文字输入区域
                      Expanded(
                        flex: selectedImagePath != null ? 1 : 2,
                        child: TextField(
                          controller: _textController,
                          textInputAction: TextInputAction.done,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 20.sp,
                            fontFamily: 'ReenieBeanie',
                            fontWeight: FontWeight.w500,
                          ),
                          maxLines: null,
                          minLines: 1,
                          keyboardType: TextInputType.multiline,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            enabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                            errorBorder: InputBorder.none,
                            disabledBorder: InputBorder.none,
                            contentPadding: EdgeInsets.all(16),
                            hintText: 'Please Enter Text......',
                            hintStyle: TextStyle(
                              color: Colors.black.withValues(alpha: 0.5),
                              fontSize: 20.sp,
                              fontFamily: 'ReenieBeanie',
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                      // 图片显示区域或加载状态
                      if (selectedImagePath != null || isLoadingImage)
                        Expanded(
                          flex: 1,
                          child: Container(
                            width: double.infinity,
                            margin: EdgeInsets.all(16.w),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8.r),
                              border: Border.all(
                                color: const Color(0xFFFF7700),
                                width: 1.w,
                              ),
                            ),
                            child: isLoadingImage
                                ? _buildImageLoadingWidget()
                                : FutureBuilder<String?>(
                                    future: _getFullImagePath(
                                      selectedImagePath!,
                                    ),
                                    builder: (context, snapshot) {
                                      if (snapshot.hasData &&
                                          snapshot.data != null) {
                                        return Stack(
                                          children: [
                                            ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(8.r),
                                              child: Image.file(
                                                File(snapshot.data!),
                                                fit: BoxFit.cover,
                                                width: double.infinity,
                                                height: double.infinity,
                                                errorBuilder:
                                                    (
                                                      context,
                                                      error,
                                                      stackTrace,
                                                    ) {
                                                      return Container(
                                                        color: Colors.grey
                                                            .withValues(
                                                              alpha: 0.3,
                                                            ),
                                                        child: Center(
                                                          child: Column(
                                                            mainAxisAlignment:
                                                                MainAxisAlignment
                                                                    .center,
                                                            children: [
                                                              Icon(
                                                                Icons
                                                                    .error_outline,
                                                                color:
                                                                    Colors.grey,
                                                                size: 32.sp,
                                                              ),
                                                              SizedBox(
                                                                height: 8.h,
                                                              ),
                                                              Text(
                                                                'Image not found',
                                                                style: TextStyle(
                                                                  color: Colors
                                                                      .grey,
                                                                  fontSize:
                                                                      12.sp,
                                                                ),
                                                              ),
                                                            ],
                                                          ),
                                                        ),
                                                      );
                                                    },
                                              ),
                                            ),
                                            // 成功上传动画覆盖层
                                            if (imageUploadSuccess)
                                              _buildSuccessOverlay(),
                                            // 删除按钮
                                            Positioned(
                                              top: 8.w,
                                              right: 8.w,
                                              child: GestureDetector(
                                                onTap: _removeImage,
                                                child: Container(
                                                  width: 28.w,
                                                  height: 28.w,
                                                  decoration: BoxDecoration(
                                                    color: Colors.black
                                                        .withValues(alpha: 0.6),
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                          14.r,
                                                        ),
                                                  ),
                                                  child: Icon(
                                                    Icons.close,
                                                    color: Colors.white,
                                                    size: 16.sp,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ],
                                        );
                                      } else {
                                        // 加载中或加载失败时显示占位符
                                        return Container(
                                          color: Colors.grey.withValues(
                                            alpha: 0.1,
                                          ),
                                          child: Center(
                                            child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                SizedBox(
                                                  width: 24.w,
                                                  height: 24.w,
                                                  child: CircularProgressIndicator(
                                                    strokeWidth: 2.w,
                                                    valueColor:
                                                        AlwaysStoppedAnimation<
                                                          Color
                                                        >(Color(0xFFFF7700)),
                                                  ),
                                                ),
                                                SizedBox(height: 8.h),
                                                Text(
                                                  'Loading image...',
                                                  style: TextStyle(
                                                    color: Color(0xFFFF7700),
                                                    fontSize: 12.sp,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        );
                                      }
                                    },
                                  ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),

              // 上传图片按钮 - 只在没有图片且不在加载时显示
              if (selectedImagePath == null && !isLoadingImage)
                Positioned(
                  bottom: 40.h,
                  right: 25.w,
                  child: GestureDetector(
                    onTap: _pickImage,
                    child: Icon(
                      Icons.photo_size_select_actual,
                      color: Color(0xffF09400),
                      size: 28.sp,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

// 时间选择弹窗组件
class _TimeSelectionDialog extends StatefulWidget {
  final Function(String) onTimeSelected;

  const _TimeSelectionDialog({required this.onTimeSelected});

  @override
  State<_TimeSelectionDialog> createState() => _TimeSelectionDialogState();
}

class _TimeSelectionDialogState extends State<_TimeSelectionDialog> {
  String _selectedTime = '';
  final List<String> _timeOptions = [
    'Random',
    'Half a Year',
    'One Year',
    'Five Years',
    'Ten Years',
  ];

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        width: 330.w,
        height: 391.h,
        decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.r),
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 顶部图片
            Image.asset(
              MyImages.timeCapsuleSelect,
              width: 170.w,
              height: 170.h,
              fit: BoxFit.contain,
            ),
            // 标题
            SizedBox(
              width: 268.w,
              child: Text(
                'Select a Sending Date',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Color(0xFF100F11),
                  fontSize: 20.sp,
                  fontFamily: 'Quicksand',
                  fontWeight: FontWeight.w600,
                  height: 1.35.h,
                  letterSpacing: 0.20.sp,
                ),
              ),
            ),
            SizedBox(height: 10.h),
            // 时间选择按钮
            Wrap(
              spacing: 10.w,
              runSpacing: 10.h,
              alignment: WrapAlignment.center,
              runAlignment: WrapAlignment.center,
              children: _timeOptions.map((time) {
                final isSelected = _selectedTime == time;
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedTime = time;
                    });
                  },
                  child: Container(
                    width: 90.w,
                    height: 31.h,
                    decoration: ShapeDecoration(
                      color: isSelected ? Color(0xFFFF8E04) : null,
                      shape: RoundedRectangleBorder(
                        side: BorderSide(width: 1.w, color: Color(0xFFFF8E03)),
                        borderRadius: BorderRadius.circular(14.r),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        time,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: isSelected
                              ? Colors.white
                              : const Color(0xFFFF8E04),
                          fontSize: 14.sp,
                          fontFamily: 'Quicksand',
                          fontWeight: FontWeight.w600,
                          height: 1.93.h,
                          letterSpacing: 0.14.sp,
                        ),
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
            SizedBox(height: 20.h),
            // 确认按钮
            GestureDetector(
              onTap: () {
                if (_selectedTime.isNotEmpty) {
                  context.goBack();
                  widget.onTimeSelected(_selectedTime);
                }
              },
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                child: Container(
                  width: 295.w,
                  height: 51.h,
                  padding: EdgeInsets.symmetric(
                    horizontal: 10.w,
                    vertical: 12.h,
                  ),
                  decoration: ShapeDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.00, 0.50),
                      end: Alignment(1.00, 0.50),
                      colors: [Color(0xFFFF8C00), Color(0xFFF8FFC7)],
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                    shadows: [
                      BoxShadow(
                        color: Color(0x190D0A14),
                        blurRadius: 14.r,
                        offset: Offset(0, 8.r),
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    spacing: 10.w,
                    children: [
                      Text(
                        'Confirm',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontFamily: 'PingFang SC',
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }
}
